<script>
$(document).ready(function(){
	function Budget(data){
		console.log('Creating budget entry');
		console.log(data);
		this._id = ko.observable(data._id);
		this.name = ko.observable(data.name);
	}
	
	function ViewBudgetsViewModel(){
		var self = this;
		this.budgets = ko.observableArray([]);
		
		self.Delete = function(budget){
			self.budgets.remove(budget);
		}
		
		$.getJSON('/action/get_data', {model_name: 'budget'}, function(docs){
			if(docs.length == 0){
				console.log('No budgets for current user');
				return;
			}
			var mapped_budgets = $.map(docs, function(item){ return new Budget(item); });
			self.budgets(mapped_budgets);
		});
	}
	
	ko.applyBindings(new ViewBudgetsViewModel()); 
});

function DeleteBudget(id){
	$.post('/action/delete', {model_name: 'budget', id: id}, function(){}, 'JSON');
}
</script>

<h2> View Budgets </h2>
<table id='budgets' data-bind='foreach: budgets'>
	<tr>
		<td data-bind='text: name'></td>
		<td><a href='#' data-bind='attr: {href: "/view/view_budget?id="+_id()}'>View</a></td>
		<td><a href='#' data-bind='attr: {href: "/view/edit_incomes?id="+_id()} '>Edit</a></td>
		<td><a href='#' data-bind='attr: {onclick: "DeleteBudget("+_id()+")"}'>Delete</a></td>
	</tr>
</table>